﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFServices.Models;
using WPFServices.Models.Domain;

namespace WPFServices.Services.DomainService.BomInfo
{
    public class BomService
    {
        private readonly ApiClient _apiClient;

        public BomService()
        {
            _apiClient = new ApiClient();
        }

        /// <summary>
        /// 获取所有Bom
        /// </summary>
        public async Task<ApiPaging<List<BomDto>>> SearchBomAsync(SearchBomDto searchBomDto)
        {
            var queryParams = $"PageIndex={searchBomDto.PageIndex}&PageSize={searchBomDto.PageSize}";
            if (!string.IsNullOrEmpty(searchBomDto.BomCode))
            {
                queryParams += $"&BomCode={Uri.EscapeDataString(searchBomDto.BomCode)}";
            }
            if (!string.IsNullOrEmpty(searchBomDto.ProductName))
            {
                queryParams += $"&ProductName={Uri.EscapeDataString(searchBomDto.ProductName)}";
            }
            if (!string.IsNullOrEmpty(searchBomDto.BomVersion))
            {
                queryParams += $"&BomVersion={Uri.EscapeDataString(searchBomDto.BomVersion)}";
            }

            var result = await _apiClient.GetAsync<ApiPaging<List<BomDto>>>($"Bom/GetBom?{queryParams}");
            if (result.IsSuc && result.code == ResultCode.Ok)
            {
                return result.data;
            }
            else
            {
                throw new Exception($"获取流程列表失败: {result.msg}");
            }
        }

        /// <summary>
        /// 新增Bom
        /// </summary>
        public async Task<BomDto> CreateBomAsync(CreateorUpdateBomDto createorUpdateBomDto)
        {
            try
            {
                var result = await _apiClient.PostAsync<BomDto>("Bom/CreateBom", createorUpdateBomDto);

                if (result.IsSuc && result.code == ResultCode.Ok)
                {
                    return result.data;
                }
                else
                {
                    throw new Exception($"新增Bom失败: {result.msg}");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"新增Bom失败: {ex.Message}");
            }
        }
    }
}
